import random

import gradio as gr

import time

# 一个随机回答是或否的聊天机器人
def random_response(message, history):
    return random.choice(["Yes", "No"])


# 结合用户输入和历史记录的示例
def alternatingly_agree(message, history):
    if len(history) % 2 == 0:
        return f"Yes, I do think that '{message}'"
    else:
        return "I don't think so"

# 流式聊天机器人
def slow_echo(message, history):
    for i in range(len(message)):
        time.sleep(0.3)
        yield "You typed: " + message[: i+1]


# 附加输入，为你的聊天机器人添加额外的参数，并通过聊天机器人UI向用户展示它们
# 想添加一个用于系统提示的文本框，或者一个设置聊天机器人响应中令牌数量的滑块。
# ChatInterface类支持一个additional_inputs参数，可以用来添加额外的输入组件
def echo(message, history, system_prompt, tokens):
    response = f"System prompt: {system_prompt}\n Message: {message}."
    for i in range(min(len(response), int(tokens))):
        time.sleep(0.05)
        yield response[: i + 1]

demo = gr.ChatInterface(
    echo,
    additional_inputs=[
        gr.Textbox("You are helpful AI.", label="System Prompt"),
        gr.Slider(10, 100),
    ],
)
demo.queue().launch()
# gr.ChatInterface(slow_echo).launch()
